﻿using System.Text;
using System.IO;
using ProtoBuf;

namespace Protobuf
{
	class ProtobufHelper
	{
		/// <summary>
		/// 序列化
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="t"></param>
		/// <returns>返回字符串</returns>
		public static string Serialize<T>(T t)
		{
			using (MemoryStream ms = new MemoryStream())
			{
				Serializer.Serialize<T>(ms, t);
				return Encoding.UTF8.GetString(ms.ToArray());
			}
		}

		public static void SerializeToFile<T>(string path, T data)
		{
			using (Stream file = File.Create(path))
			{
				Serializer.Serialize<T>(file, data);
				file.Close();
			}
		}

		/// <summary>
		/// 根据字符串反序列化成对象
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="content"></param>
		/// <returns></returns>
		public static T DeSerialize<T>(string content)
		{
			using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(content)))
			{
				T t = Serializer.Deserialize<T>(ms);
				return t;
			}
		}

		/// <summary>
		/// 根据文件流返回对象
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="filestream"></param>
		/// <returns></returns>
		public static T DeSerialize<T>(Stream filestream)
		{
			return Serializer.Deserialize<T>(filestream);
		}

	}
}
